package cs342.uwosh.edu.MyWorldApp.cloud;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import cs342.uwosh.edu.MyWorldApp.storage.Friend;
import cs342.uwosh.edu.MyWorldApp.storage.Location;
import cs342.uwosh.edu.MyWorldApp.storage.User;

//import encryption.RESEncryption;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class CloudLinker extends SQLiteOpenHelper {
	String user = "", pass = "", timeStamp;
	byte[] data;
	HttpPost httppost;
	StringBuffer buffer;
	HttpResponse response;
	HttpClient httpclient;
	InputStream inputStream;
	SharedPreferences app_preferences;
	List<NameValuePair> nameValuePairs;
	public static final String DB_NAME = "contactDB.db";
	public static final int bufferSize = 1024;
	private static final String RES_KEY = "9466721455493";
	public static User currentUser;
	//private RESEncryption myRes;

	public CloudLinker(Context context) {
		super(context, DB_NAME, null, 1);
		//myRes = new RESEncryption(RES_KEY);
	}

	public String checkUser(String userName, String passWord) {
		try {

			user = userName;
			pass = passWord;
			httpclient = new DefaultHttpClient();
			httppost = new HttpPost("http://173.89.153.5/p4.php?login");

			nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("user", user.trim()));
			nameValuePairs.add(new BasicNameValuePair("pass", pass.trim()));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			response = httpclient.execute(httppost);
			inputStream = response.getEntity().getContent();

			data = new byte[256];

			buffer = new StringBuffer();
			int len = 0;
			while (-1 != (len = inputStream.read(data))) {
				buffer.append(new String(data, 0, len));
			}

			inputStream.close();
		} catch (Exception e) {
			return e.toString();
		}
		try {
			return buffer.toString();
		} catch (NullPointerException e) {
			return "Permission denied";
		}
	}
	
	public String doRegister(String username, String password) {
		try {

			httpclient = new DefaultHttpClient();
			httppost = new HttpPost("http://173.89.153.5/p4.php?register&user=" + username + "&pass=" + password);

			nameValuePairs = new ArrayList<NameValuePair>(2);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			response = httpclient.execute(httppost);
			inputStream = response.getEntity().getContent();

			data = new byte[256];

			buffer = new StringBuffer();
			int len = 0;
			while (-1 != (len = inputStream.read(data))) {
				buffer.append(new String(data, 0, len));
			}

			inputStream.close();
		} catch (Exception e) {
			return e.toString();
		}
		try {
			return buffer.toString();
		} catch (NullPointerException e) {
			return "Permission denied";
		}
	}
	
	public String[] getFriendsList(String username) {
		try {

			httpclient = new DefaultHttpClient();
			httppost = new HttpPost("http://173.89.153.5/p4.php?flist&user=" + username);

			nameValuePairs = new ArrayList<NameValuePair>(2);
			response = httpclient.execute(httppost);
			inputStream = response.getEntity().getContent();

			data = new byte[256];

			buffer = new StringBuffer();
			int len = 0;
			while (-1 != (len = inputStream.read(data))) {
				buffer.append(new String(data, 0, len));
			}

			inputStream.close();
		} catch (Exception e) {
			return null;
		}
		try {
			return buffer.toString().split("\\+");
		} catch (NullPointerException e) {
			return null;
		}
	}
	
	
	public String getLocation(String username) {
		try {

			httpclient = new DefaultHttpClient();
			httppost = new HttpPost("http://173.89.153.5/p4.php?getlocation&user=" + username);

			nameValuePairs = new ArrayList<NameValuePair>(2);
			response = httpclient.execute(httppost);
			inputStream = response.getEntity().getContent();

			data = new byte[256];

			buffer = new StringBuffer();
			int len = 0;
			while (-1 != (len = inputStream.read(data))) {
				buffer.append(new String(data, 0, len));
			}

			inputStream.close();
		} catch (Exception e) {
			return e.toString();
		}
		try {
			return buffer.toString();
		} catch (NullPointerException e) {
			return "Data not returned from server";
		}
	}
	
	public String getVisibility(String username) {
		try {

			httpclient = new DefaultHttpClient();
			httppost = new HttpPost("http://173.89.153.5/p4.php?getvisible&user=" + username);

			nameValuePairs = new ArrayList<NameValuePair>(2);
			response = httpclient.execute(httppost);
			inputStream = response.getEntity().getContent();

			data = new byte[256];

			buffer = new StringBuffer();
			int len = 0;
			while (-1 != (len = inputStream.read(data))) {
				buffer.append(new String(data, 0, len));
			}

			inputStream.close();
		} catch (Exception e) {
			return e.toString();
		}
		try {
			return buffer.toString();
		} catch (NullPointerException e) {
			return "Data not returned from server";
		}
	}
	
	
	public String sendLocation(String username, String location) {
		try {

			httpclient = new DefaultHttpClient();
			httppost = new HttpPost("http://173.89.153.5/p4.php?sendlocation&user=" + username + "&location=" + location);

			nameValuePairs = new ArrayList<NameValuePair>(2);
			response = httpclient.execute(httppost);
			inputStream = response.getEntity().getContent();

			data = new byte[256];

			buffer = new StringBuffer();
			int len = 0;
			while (-1 != (len = inputStream.read(data))) {
				buffer.append(new String(data, 0, len));
			}

			inputStream.close();
		} catch (Exception e) {
			return e.toString();
		}
		try {
			return buffer.toString();
		} catch (NullPointerException e) {
			return "Data not returned from server";
		}
	}
	
	
	public String addFriend(String username, String friend) {
		try {

			httpclient = new DefaultHttpClient();
			httppost = new HttpPost("http://173.89.153.5/p4.php?addfriend&user=" + username + "&friend=" + friend);

			nameValuePairs = new ArrayList<NameValuePair>(2);
			response = httpclient.execute(httppost);
			inputStream = response.getEntity().getContent();

			data = new byte[256];

			buffer = new StringBuffer();
			int len = 0;
			while (-1 != (len = inputStream.read(data))) {
				buffer.append(new String(data, 0, len));
			}

			inputStream.close();
		} catch (Exception e) {
			return e.toString();
		}
		try {
			return buffer.toString();
		} catch (NullPointerException e) {
			return "Data not returned from server";
		}
	}
	
	public String setVisibility(String username, boolean visible) {
		try {
			String v = "0";
			if (visible)
				v = "1";
			httpclient = new DefaultHttpClient();
			httppost = new HttpPost("http://173.89.153.5/p4.php?toggleinvis&user=" + username + "&invis=" + v);

			nameValuePairs = new ArrayList<NameValuePair>(2);
			response = httpclient.execute(httppost);
			inputStream = response.getEntity().getContent();

			data = new byte[256];

			buffer = new StringBuffer();
			int len = 0;
			while (-1 != (len = inputStream.read(data))) {
				buffer.append(new String(data, 0, len));
			}

			inputStream.close();
		} catch (Exception e) {
			return e.toString();
		}
		try {
			return buffer.toString();
		} catch (NullPointerException e) {
			return "Data not returned from server";
		}
	}
	
	
	public User initializeUser(String name) {
		String location = getLocation(name);
		String visible = getVisibility(name);
		Location loc;
		if (!location.equals("")) {
			double lon = Double.parseDouble(location.split("/")[0]) * 1000000;
			double lat = Double.parseDouble(location.split("/")[1]) * 1000000;
			int n = (int)Math.round(lon);
			int t = (int)Math.round(lat);
			loc = new Location(n, t);
		}
		else
			loc = new Location(12345678,12345678);
				
		boolean vis;
		if (visible.equals("0"))
			vis = true;
		else
			vis = false;
		
		User user = new User(name, loc, vis);
		String[] flist = getFriendsList(user.getUserName());
		for (int i = 0; i < flist.length; i++) {
			initializeFriend(flist[i], user);
		}
		
		return user;
	}
	
	public void initializeFriend(String name, User user) {
		String location = getLocation(name);
		String visible = getVisibility(name);
		Location loc;
		if (!location.equals("")) {
			double lon = Double.parseDouble(location.split("/")[0]) * 1000000;
			double lat = Double.parseDouble(location.split("/")[1]) * 1000000;
			int n = (int)Math.round(lon);
			int t = (int)Math.round(lat);
			loc = new Location(n, t);
		}
		else
			loc = new Location(12345678,12345678);
		boolean vis;
		if (visible.equals("0"))
			vis = false;
		else
			vis = true;
		
		Friend friend = new Friend(name, loc);
		//TODO What about visibility?
		user.addFriend(friend);
		
	}
	
	
	public void UpdateFriendsLocations(User user) {
		String[] flist = getFriendsList(user.getUserName());
		
		for (int i = 0; i < flist.length; i++) {
			String location = getLocation(flist[i]);
			String visible = getVisibility(flist[i]);
			//TODO What do you want to do with this?
			int lon = Integer.parseInt(location.split("/")[0]);
			int lat = Integer.parseInt(location.split("/")[1]);
			Location loc = new Location(lon,lat);
			int index = 0;
			for (int j = 0; j < user.friendsList.size(); i++) {
				if (user.friendsList.get(j).getUserName().equals(flist[i]))
					index = j;
			}
			user.friendsList.get(index).setLocation(loc);
		}
		
	}
	// For get friends coords return 2 element array of strings as seen in MyWorldAppActivity

	@Override
	public void onCreate(SQLiteDatabase arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}
}
